﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using TagCore;
using HtmlAgilityPack;

namespace GoogleQuery
{
    public class GoogleSearch : GoogleWeb, IMusicQuery
    {
        private const string searchUrl = "http://www.google.co.uk/search?tbm=isch&hl=en&source=hp&q={0}&gbv=2&oq={0}&biw=1280&bih=768";
        private const string resultRoot = "http://www.google.co.uk";

        public string Provider()
        {
            return "Google Search";
        }

        public IMusicData[] Search(IMusicData data, QueryFields fields)
        {
            // build search string
            string srch = string.Empty;
            if ((fields & QueryFields.Artist) == QueryFields.Artist)
                srch = AddSearchValue(srch, data.Artists[0]);
            if ((fields & QueryFields.Title) == QueryFields.Title)
                srch = AddSearchValue(srch, data.Title);
            if ((fields & QueryFields.Year) == QueryFields.Year)
                srch = AddSearchValue(srch, data.Year.ToString());
           
            // do request
            List<IMusicData> results = new List<IMusicData>();

            HtmlNodeCollection nodes = GetResults(srch);
            int resultCount = Math.Min(10, nodes.Count);
            for (int loop = 0; loop < resultCount; loop++)
            {
                GoogleResponse resp = new GoogleResponse(resultRoot, nodes[loop]);
                results.Add(resp);
            }

            return results.ToArray();           
        }

        private HtmlNodeCollection GetResults(string srch)
        {
            string url = HttpUtility.UrlEncode(srch);
            url = string.Format(searchUrl, url);
           
            byte[] res = GetWebRequest(url);
            MemoryStream ms = new MemoryStream(res);
            doc.Load(ms);

            return doc.DocumentNode.SelectNodes("//a[@class='rg_l']");
        }

        private string AddSearchValue(string srch, string val)
        {
            if (srch.Length > 0)
                srch += " ";
            srch += val;
            return srch;
        }
            
    }
}
